from analyse.tool.code_help import dprint
import numpy as np
import sympy
from scipy.constants import *
from analyse.tool.code_help import *
#=========单位、数量级===============================================
femto = 1e-15
micron = 1e-6
pi = np.pi
#==========常用物理量=================================================
qe = e
me = m_e
epsilon0 = epsilon_0
h_bar = hbar


class parameter_simulation:
    def str_hander(self, str):
        '''
        用于处理读入的一行
        1.先去掉所有空格
        2.如果首字字母是#，则返回''；如果字符串含有x，y等表达式，返回''
        3.法语替换
        4.str1返回语法替换后的字符串
        5.str2返回"self.var=var"
        '''
        temp_str1 = str.strip()
        temp_str1 = temp_str1.replace('\ ', '')
        # dprint('here in str_hander:', type(temp_str1), len(temp_str1),
        #        temp_str1)
        #处理特殊情况
        if (len(temp_str1) == 0) or (temp_str1[0] == '#'):  #空字符行或者首字母为#返回空
            return '', '', ''
        if ('#analyse_omit#' in temp_str1):
            return '', '', ''
        #语法替换
        temp_str1 = temp_str1.replace('^', '**')
        temp_str1 = temp_str1.replace('sqrt', 'sympy.sqrt')
        temp_str1 = temp_str1.replace('atan', 'sympy.atan')
        temp_str1 = temp_str1.replace('exp', 'sympy.exp')
        temp_str1 = temp_str1.replace('loge', 'sympy.log')
        if ('qed_maxwell_solver' in temp_str1):
            if ('T' in temp_str1):
                temp_str1 = 'qed_maxwell_solver=True'
            elif ('F' in temp_str1):
                temp_str1 = 'qed_maxwell_solver=False'
        if ('gauss' in temp_str1):
            temp = temp_str1.index('(')
            temps = temp_str1[temp + 1:-1]
            temps = temps.split(',')
            temp_str1 = temp_str1[0:temp]
            temp_str1 = temp_str1.replace('gauss', 'sympy.exp')
            temp_str1 = temp_str1 + '(-((' + temps[0] + '-' + temps[
                1] + ')/' + temps[2] + ')**2)'

        # temp_str1 = temp_str1.replace('gauss', 'sympy.gauss')
        #返回结果
        temp_index = temp_str1.find("=")
        temp_var = temp_str1[0:temp_index]
        temp_var = temp_var.strip()
        temp_str2 = 'self.' + temp_var + '=' + temp_var
        return temp_str1, temp_str2, temp_var

    #=============统计区间，参数========================================
    def __init__(self, dim, path='') -> None:
        self.dim = dim
        try:
            #with 函数，在函数段运行结束后会调用__eixt__()，用在文件里面是是调用文件关闭函数
            fh = open(path, "r")

        except FileNotFoundError:
            print("Error: 没有找到文件或读取文件失败")
            return None
        else:
            #flag设置，标志每个参数模块有没有被读入
            plasma = 0
            laser = 0
            basic = 0
            x = sympy.Symbol('x')
            y = sympy.Symbol('y')
            z = sympy.Symbol('z')
            time = sympy.Symbol('time')
            text_lines = fh.readlines()
            i = 0
            while (i < len(text_lines)):
                str = text_lines[i]
                if 'begin plasma set' in str:
                    dprint('开始读入plasma参数')
                    flag = 1
                    i = i + 1
                    temp = text_lines[i]
                    while ('end plasma set' not in temp):
                        dprint('原读入字符串：', temp)
                        #读取下面每一行，并转化为变量
                        temp_str1, temp_str2, temp_var = self.str_hander(temp)
                        if (temp_var != ''):
                            exec('global ' + temp_var)
                        exec(temp_str1)
                        exec(temp_str2)
                        dprint("已读入第%i个数据(字符串处理之后)" % flag, temp_str1)
                        i = i + 1
                        temp = text_lines[i]
                        flag += 1
                        if (flag >= 100):
                            dprint("异常：plasma 设置超过100行，无法处理")
                            break
                    dprint('结束读入plasma参数')
                elif ('begin laser set' in str):
                    dprint('开始读入laser参数')
                    flag = 1
                    i = i + 1
                    temp = text_lines[i]
                    while ('end laser set' not in temp):
                        #读取下面每一行，并转化为变量
                        dprint('原读入字符串：', temp)
                        temp_str1, temp_str2, temp_var = self.str_hander(temp)
                        dprint("第%i个数据(字符串处理之后)" % flag, temp_str1)
                        if (temp_var != ''):
                            exec('global ' + temp_var)
                        exec(temp_str1)
                        exec(temp_str2)
                        i = i + 1
                        temp = text_lines[i]
                        flag += 1
                        if (flag >= 100):
                            dprint("异常：laser 设置超过100行，无法处理")
                            break
                    dprint('结束读入laser参数')
                    # dprint(period_T_1)
                elif ('begin basic set' in str):
                    dprint('开始读入basic参数')
                    flag = 1
                    i = i + 1
                    temp = text_lines[i]
                    while ("end basic set" not in temp):
                        #读取下面每一行，并转化为变量
                        dprint('原读入字符串：', temp)
                        temp_str1, temp_str2, temp_var = self.str_hander(temp)
                        dprint("第%i个数据(字符串处理之后)" % flag, temp_str1)
                        if (temp_var != ''):
                            exec('global ' + temp_var)
                        exec(temp_str1)
                        exec(temp_str2)
                        i = i + 1
                        temp = text_lines[i]
                        flag += 1
                        if (flag >= 100):
                            dprint("异常：basic设置超过100行，无法处理")
                            break
                    dprint('结束读入basic参数')
                    # dprint(simtime)
                elif ('begin:control' in str):
                    dprint('开始读入control参数')
                    # dprint(globals()['simtime'])
                    flag = 1
                    i = i + 1
                    temp = text_lines[i]
                    while ("end:control" not in temp):
                        #读取下面每一行，并转化为变量
                        dprint('原读入字符串：', temp)
                        temp_str1, temp_str2, temp_var = self.str_hander(temp)
                        dprint("第%i个数据(字符串处理之后)" % flag, temp_str1)
                        if (temp_var != ''):
                            exec('global ' + temp_var)
                        # dprint(locals())
                        exec(temp_str1)
                        exec(temp_str2)
                        i = i + 1
                        temp = text_lines[i]
                        flag += 1
                        if (flag >= 100):
                            dprint("异常：control设置超过100行，无法处理")
                            break
                    dprint('end:control')
                else:
                    i += 1
            print('读取模拟数据成功')
            fh.close()
        #==========模拟参数===================================================
        # self.sdf_dim = sdf_dim
        # #------laser------------
        # self.laser_wavelength = laser_wavelength
        # self.laser_frequency = laser_frequency
        # self.laser_k = laser_k
        # self.laser_wavenumber = laser_wavenumber
        # self.laser_T = laser_T
        # self.laser_a = laser_a
        # self.laser_E = laser_E
        # #-----grid--------------
        # self.nx = nx
        # self.ny = ny
        # self.xmin = xmin
        # self.xmax = xmax
        # self.ymin = ymin
        # self.ymax = ymax
